import { login, logout } from "../../api/user";

const state = JSON.parse(localStorage.getItem("user")) ||
  JSON.parse(sessionStorage.getItem("user")) || {
    name: "",
    nickName: "",
    token: "",
    userId: "",
  };
const actions = {
  async login({ commit }, { phone, password }) {
    try {
      const res = await login(phone, password);
      console.log("actions==>", res);
      commit("LOGIN", res);
      return res;
    } catch (error) {
      console.log(error);
    }
  },

  async logout({ commit }) {
    try {
      // 向服务器发送登出请求
      await logout();
      // 清除localStorage上的user数据
      localStorage.removeItem("user");
      // 清除sessionStorage上的user数据
      sessionStorage.removeItem("user");
      commit("LOGOUT");
    } catch (error) {
      console.log(error);
    }
  },
};
const mutations = {
  LOGIN(state, res) {
    state.name = res.name;
    state.nickName = res.nickName;
    state.token = res.token;
    state.userId = res.userId;
  },
  // 清空登录信息
  LOGOUT(state) {
    state.name = "";
    state.nickName = "";
    state.token = "";
    state.userId = "";
  },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
};
